<template>
  <div class="profile-container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-content">
        <div class="title">智慧医疗平台</div>
        <div class="header-actions">
          <van-popover
            v-model:show="showPopover"
            placement="bottom-end"
            :actions="popoverActions"
            @select="onPopoverSelect"
          >
            <template #reference>
              <van-icon name="ellipsis" size="20" />
            </template>
          </van-popover>
          <van-icon name="setting-o" size="20" style="margin-left: 12px" @click="goToSettings" />
        </div>
      </div>
    </div>

    <!-- 用户信息区域 -->
    <div class="user-section">
      <div class="user-info">
        <div class="user-avatar">
          <van-image
            round
            width="50"
            height="50"
            src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"
          />
        </div>
        <div class="user-details">
          <div class="user-name">{{ userInfo.realName || '未登录' }}</div>
          <div class="user-subtitle">实名认证人员信息 ></div>
        </div>
      </div>
      <div class="family-management">
        <div class="family-card">
          <div class="card-title">{{ userInfo.realName || '王特' }} (本人)</div>
          <div class="card-number">登记号：{{ userInfo.id || '123456789' }}</div>
          <van-icon name="qr" class="qr-icon" />
        </div>
      </div>
    </div>

    <!-- 诊疗记录 -->
    <div class="medical-records">
      <div class="section-title">诊疗记录</div>
      <div class="records-grid">
        <div class="record-item" v-for="record in medicalRecords" :key="record.id" @click="handleRecordClick(record)">
          <van-icon :name="record.icon" size="24" class="record-icon" />
          <span class="record-text">{{ record.title }}</span>
        </div>
      </div>
    </div>

    <!-- 服务设置 -->
    <div class="service-settings">
      <div class="section-title">服务设置</div>
      <div class="settings-grid">
        <div class="setting-item" v-for="setting in serviceSettings" :key="setting.id" @click="handleSettingClick(setting)">
          <van-icon :name="setting.icon" size="24" class="setting-icon" />
          <span class="setting-text">{{ setting.title }}</span>
        </div>
      </div>
    </div>



    <!-- 底部导航栏 -->
    <div class="tabbar-container">
      <van-tabbar v-model="activeTab" @change="onTabChange">
        <van-tabbar-item icon="home-o" name="home">医疗服务</van-tabbar-item>
        <van-tabbar-item icon="search" name="search">智慧问诊</van-tabbar-item>
        <van-tabbar-item icon="friends-o" name="message">消息中心</van-tabbar-item>
        <van-tabbar-item icon="setting-o" name="profile">我的</van-tabbar-item>
      </van-tabbar>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Toast, Dialog } from 'vant'

/**
 * 个人中心页面组件
 * 提供用户信息展示、健康档案、功能菜单等功能
 */

const router = useRouter()
const activeTab = ref('profile')
const isLoggedIn = ref(false)
const orderCount = ref(3)
const reportCount = ref(2)
const showPopover = ref(false)

/**
 * 省略号菜单选项
 */
const popoverActions = ref([
  { text: '退出登录', icon: 'sign-out', color: '#ee0a24' }
])

/**
 * 用户信息
 */
const userInfo = reactive({
  id: '2015****10',
  realName: 'StarKun',
  phone: '138****8888',
  avatar: '',
  registrationNumber: '2015****10'
})

/**
 * 诊疗记录数据
 */
const medicalRecords = ref([
  { id: 1, title: '挂号订单', icon: 'calendar-o' },
  { id: 2, title: '医嘱订单', icon: 'description' },
  { id: 3, title: '就诊记录', icon: 'records' },
  { id: 4, title: '门诊病历', icon: 'completed' }
])

/**
 * 服务设置数据
 */
const serviceSettings = ref([
  { id: 1, title: '我的关注', icon: 'star-o' },
  { id: 2, title: '地址管理', icon: 'location-o' },
  { id: 3, title: '意见反馈', icon: 'chat-o' },
  { id: 4, title: '帮助中心', icon: 'question-o' },
  { id: 5, title: '信用守约', icon: 'certificate' },
  { id: 6, title: '关于我们', icon: 'info-o' },
  { id: 7, title: '设置', icon: 'setting-o' }
])

/**
 * 返回上一页
 */
const onClickLeft = () => {
  router.back()
}

/**
 * 跳转到设置页面
 */
const goToSettings = () => {
  Toast('设置功能开发中...')
}

/**
 * 处理省略号菜单选择
 * @param action 选择的菜单项
 */
const onPopoverSelect = (action: any) => {
  showPopover.value = false
  
  switch (action.text) {
    case '退出登录':
      logout()
      break
    default:
      Toast(`${action.text}功能开发中...`)
  }
}

/**
 * 跳转到登录页面
 */
const goToLogin = () => {
  router.push('/login')
}

/**
 * 跳转到开单记录
 */
const goToOrderHistory = () => {
  router.push('/order-history')
}

/**
 * 跳转到预约挂号
 */
const goToAppointment = () => {
  Toast('预约挂号功能开发中...')
}

/**
 * 跳转到检查报告
 */
const goToReports = () => {
  Toast('检查报告功能开发中...')
}

/**
 * 跳转到缴费记录
 */
const goToPaymentHistory = () => {
  Toast('缴费记录功能开发中...')
}

/**
 * 跳转到健康档案
 */
const goToHealthProfile = () => {
  Toast('健康档案功能开发中...')
}

/**
 * 跳转到用药提醒
 */
const goToMedicineReminder = () => {
  Toast('用药提醒功能开发中...')
}

/**
 * 跳转到体检报告
 */
const goToPhysicalExam = () => {
  Toast('体检报告功能开发中...')
}

/**
 * 跳转到健康资讯
 */
const goToHealthNews = () => {
  Toast('健康资讯功能开发中...')
}

/**
 * 跳转到账户设置
 */
const goToAccountSettings = () => {
  Toast('账户设置功能开发中...')
}

/**
 * 跳转到消息通知设置
 */
const goToNotificationSettings = () => {
  Toast('消息通知设置功能开发中...')
}

/**
 * 跳转到帮助中心
 */
const goToHelp = () => {
  Toast('帮助中心功能开发中...')
}

/**
 * 跳转到关于我们
 */
const goToAbout = () => {
  Toast('关于我们功能开发中...')
}

/**
 * 处理诊疗记录点击
 * @param record 记录项
 */
const handleRecordClick = (record: any) => {
  console.log('点击诊疗记录:', record)
  Toast(`${record.title}功能开发中...`)
}

/**
 * 处理服务设置点击
 * @param setting 设置项
 */
const handleSettingClick = (setting: any) => {
  console.log('点击服务设置:', setting)
  switch (setting.id) {
    case 1:
      Toast('我的关注功能开发中...')
      break
    case 2:
      Toast('地址管理功能开发中...')
      break
    case 3:
      Toast('意见反馈功能开发中...')
      break
    case 4:
      goToHelp()
      break
    case 5:
      Toast('信用守约功能开发中...')
      break
    case 6:
      goToAbout()
      break
    case 7:
      goToSettings()
      break
    default:
      Toast(`${setting.title}功能开发中...`)
  }
}

/**
 * 底部导航切换
 * @param name 导航名称
 */
const onTabChange = (name: string) => {
  console.log('切换导航:', name)
  switch (name) {
    case 'home':
      router.push('/')
      break
    case 'search':
      Toast('智慧问诊功能开发中...')
      break
    case 'message':
      Toast('消息中心功能开发中...')
      break
    case 'profile':
      // 当前页面，无需跳转
      break
  }
}

/**
 * 退出登录
 */
const logout = () => {
  Dialog.confirm({
    title: '退出登录',
    message: '确定要退出登录吗？',
  })
    .then(() => {
      // 清除登录状态
      localStorage.removeItem('userInfo')
      localStorage.removeItem('isLoggedIn')
      localStorage.removeItem('rememberedLoginData')
      
      // 重置用户信息
      userInfo.id = ''
      userInfo.realName = ''
      userInfo.phone = ''
      userInfo.avatar = ''
      isLoggedIn.value = false
      
      Toast.success('已退出登录')
      
      // 跳转到登录页面
      setTimeout(() => {
        router.replace('/login')
      }, 1000)
    })
    .catch(() => {
      // 取消退出
    })
}

/**
 * 初始化用户信息
 */
const initUserInfo = () => {
  const loginStatus = localStorage.getItem('isLoggedIn')
  const userInfoStr = localStorage.getItem('userInfo')
  
  if (loginStatus === 'true' && userInfoStr) {
    try {
      const userData = JSON.parse(userInfoStr)
      userInfo.id = userData.id
      userInfo.realName = userData.realName
      userInfo.phone = userData.phone
      userInfo.avatar = userData.avatar || ''
      isLoggedIn.value = true
    } catch (error) {
      console.error('解析用户信息失败:', error)
      isLoggedIn.value = false
    }
  } else {
    isLoggedIn.value = false
  }
}

/**
 * 页面挂载时初始化
 */
onMounted(() => {
  initUserInfo()
})
</script>

<style scoped>
.profile-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 60px;
}

.header {
  background: white;
  padding: 12px 16px;
  border-bottom: 1px solid #ebedf0;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
}

.header-actions {
  display: flex;
  align-items: center;
}

.user-section {
  background: white;
  margin: 8px 16px 16px;
  padding: 16px;
  border-radius: 8px;
}

.user-info {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
}

.user-details {
  flex: 1;
}

.user-name {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 4px;
}

.user-subtitle {
  font-size: 12px;
  color: #1989fa;
}

.family-management {
  margin-top: 12px;
}

.family-card {
  background: linear-gradient(135deg, #4285f4 0%, #1976d2 100%);
  padding: 16px;
  border-radius: 8px;
  color: white;
  position: relative;
}

.card-title {
  font-size: 14px;
  font-weight: 600;
  margin-bottom: 4px;
}

.card-number {
  font-size: 12px;
  opacity: 0.9;
}

.qr-icon {
  position: absolute;
  top: 16px;
  right: 16px;
  font-size: 24px;
}

.medical-records {
  margin: 0 16px 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 12px;
  padding-left: 4px;
}

.records-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
  background: white;
  padding: 20px;
  border-radius: 8px;
}

.record-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px 4px;
  border-radius: 8px;
  transition: background-color 0.2s;
  cursor: pointer;
  min-height: 80px;
  justify-content: center;
}

.record-item:active {
  background-color: #f2f3f5;
}

.record-icon {
  color: #1989fa;
  flex-shrink: 0;
}

.record-text {
  font-size: 11px;
  color: #323233;
  text-align: center;
  line-height: 1.2;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
}

.service-settings {
  margin: 0 16px 16px;
}

.settings-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
  background: white;
  padding: 20px;
  border-radius: 8px;
}

.setting-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  padding: 12px 8px;
  border-radius: 8px;
  transition: background-color 0.2s;
  cursor: pointer;
}

.setting-item:active {
  background-color: #f2f3f5;
}

.setting-icon {
  color: #1989fa;
}

.setting-text {
  font-size: 12px;
  color: #323233;
  text-align: center;
}



.tabbar-container {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 1000;
}
</style>